﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Security.Claims;
using System.Text.Json;
using DB.Core.Models;
using Furion;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using PMBF.Core.Enums;
using PMBF.Core.Handler;
using PMBF.Core.ViewModels;
using SqlSugar;
using StackExchange.Profiling.Internal;
using System.Linq;
using System.Dynamic;
using Newtonsoft.Json.Linq;
using System.IO;
using PMBF.Core.Plugins;

namespace PMBF.Application.Api
{
    [AppAuthorize, ApiDescriptionSettings("动态模型管理")]
    [UserApiAuthenticationActionFilter]
    public class ModelsService : IDynamicApiController
    {
        private readonly ISqlSugarRepository repository;
        private readonly SqlSugarClient db;
        private readonly int ModelId = 25;

        public ModelsService(ISqlSugarRepository sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            db = repository.Context;
        }

        #region 查询列表、编辑、保存、禁用、删除

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="_query"></param>
        /// <returns></returns>
        public Model Post(ApiModelsQuerys _query)
        {
            return Model(ModelId, _query);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="_query"></param>
        /// <returns></returns>
        [NonUnify]
        public IActionResult PostExport(ApiModelsQuerys _query)
        {
            return Export(ModelId, _query);
        }

        /// <summary>
        /// 新增编辑，获取信息
        /// </summary>
        /// <param name="_id"></param>
        /// <returns></returns>
        public dynamic GetInfo(int _id)
        {
            var page = GetEditData(ModelId);

            if (_id != 0)
            {
                page.Page.Title = "编辑模型";
                page.DataSource = db.Queryable<Model>().Where(n => n.ID == _id).First();
            }
            else
            {
                page.Page.Title = "新增模型";
            }

            return page;
        }

        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public dynamic PostSave(Model model)
        {
            bool isok = false;

            if (model.ID == 0)
            {
                model.ModifyTime = DateTime.Now;
                model.ModifyUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
                model.CreateTime = DateTime.Now;
                model.CreateUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
                model.DeleteFlag = 0;
                isok = db.Insertable(model).ExecuteCommand() > 0;
            }
            else
            {
                model.ModifyTime = DateTime.Now;
                model.ModifyUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
                isok = db.Updateable(model).IgnoreColumns(ignoreAllNullColumns: true).IgnoreColumns("CreateTime", "CreateUserID").ExecuteCommand() > 0;
            }

            if (isok == false)
            {
                throw Oops.Oh(SystemErrorCodes.E0010);
            }

            return new { Success = true, message = "保存成功" };
        }

        /// <summary>
        /// 正常数据，将数据删除标志设置成已删除
        /// </summary>
        /// <returns></returns>
        public dynamic PostDisable(ApiPostExtendModel data)
        {
            int userId = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
            foreach (int id in data.ids)
            {
                db.Updateable<Model>().SetColumns(n => new Model()
                {
                    DeleteFlag = 1,
                    DeleteTime = DateTime.Now,
                    DeleteUserID = userId
                }).Where(n => n.ID == id).ExecuteCommand();
            }

            return new { Success = true, message = "删除成功" };
        }


        /// <summary>
        /// 有数据删除标志设置的直接删除
        /// </summary>
        /// <returns></returns>
        public dynamic PostDelete(ApiPostExtendModel data)
        {
            foreach (int id in data.ids)
            {
                db.Deleteable<Model>().Where(n => n.ID == id && n.DeleteFlag == 1).ExecuteCommand();
            }

            return new { Success = true, message = "删除成功" };
        }

        /// <summary>
        /// 有数据删除标志设置的恢复
        /// </summary>
        /// <returns></returns>
        public dynamic PostRestore(ApiPostExtendModel data)
        {
            int userId = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
            foreach (int id in data.ids)
            {
                db.Updateable<Model>().SetColumns(n => new Model() { DeleteFlag = 0, ModifyTime = DateTime.Now, ModifyUserID = userId }).Where(n => n.ID == id && n.DeleteFlag == 1).ExecuteCommand();
            }

            return new { Success = true, message = "恢复成功" };
        }

        #endregion

        #region Post 获取单个Model,并获取相关的数据信息

        /// <summary>
        /// 获取单个model,相关json集
        /// </summary>
        /// <param name="_id"></param>
        /// <param name="_query"></param>
        /// <returns></returns>
        public Model Model(int _id, ApiModelsQuerys _query)
        {
            Model model = db.Queryable<Model>().Where(p => p.ID == _id).First();

            if (model == null) throw Oops.Oh(SystemErrorCodes.E0003);

            model.ObjectData = JsonConvert.DeserializeObject<PMFApiRoot>(model.Data);
            model.Data = "";
            model.EditData = "";
            model.DesignData = "";

            string orderby = "";

            for (int i = 0; i < _query.sort.Length; i++)
            {
                orderby += " " + _query.sort[i] + " " + _query.order[i] + " ,";
            }

            orderby = orderby == "" ? "id" : orderby.Substring(0, orderby.Length - 1);

            string deleteFlag = "0";

            #region 构建查询条件

            var whereModels = new List<IConditionalModel>();

            if (!string.IsNullOrEmpty(_query.queryfields))
            {
                dynamic querys = JsonConvert.DeserializeObject(_query.queryfields);
                foreach (var m in querys)
                {
                    if (m.Value == null)
                    {
                        continue;
                    }

                    if (m.Name == "id")
                    {
                        whereModels.Add(new ConditionalModel { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = m.Value.ToString() });
                    }
                    else if (m.Name == "deleteFlag")
                    {
                        deleteFlag = m.Value.ToString();
                    }
                    else
                    {
                        var tmpfield = model.ObjectData.Layout.TableColumn.FirstOrDefault(n => n.Key == m.Name.ToString());
                        if (tmpfield != null)
                        {
                            switch (tmpfield.Type)
                            {
                                case "datetime":
                                    whereModels.Add(new ConditionalModel { FieldName = m.Name.ToString(), ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = m.Value.First.ToString() });
                                    whereModels.Add(new ConditionalModel { FieldName = m.Name.ToString(), ConditionalType = ConditionalType.LessThan, FieldValue = m.Value.Last.ToString() });
                                    break;
                                case "select":
                                case "tree":
                                case "radio":
                                case "switch":
                                    whereModels.Add(new ConditionalModel { FieldName = m.Name.ToString(), ConditionalType = ConditionalType.Equal, FieldValue = m.Value.ToString() });
                                    break;
                                default:
                                    whereModels.Add(new ConditionalModel { FieldName = m.Name.ToString(), ConditionalType = ConditionalType.Like, FieldValue = m.Value.ToString() });
                                    break;
                            }
                        }
                    }
                }
            }

            //默认查询可用的，根据传递的数据进行查询删除状态
            whereModels.Add(new ConditionalModel { FieldName = "deleteFlag", ConditionalType = ConditionalType.Equal, FieldValue = deleteFlag });

            #endregion 

            if (deleteFlag == "0")
            {
                model.ObjectData.Layout.BatchToolBar.RemoveAll(n => n.UseType == "del");
                var tmpbars = model.ObjectData.Layout.TableColumn.Where(n => n.Key == "actions").FirstOrDefault();
                if (tmpbars != null)
                {
                    tmpbars.Actions.RemoveAll(n => n.UseType == "del");
                }
            }
            else
            {
                model.ObjectData.Layout.BatchToolBar.RemoveAll(n => n.UseType == "nodel");
                var tmpbars = model.ObjectData.Layout.TableColumn.Where(n => n.Key == "actions").FirstOrDefault();
                if (tmpbars != null)
                {
                    tmpbars.Actions.RemoveAll(n => n.UseType == "nodel");
                }
            }

            int totalCount = 0;
            List<dynamic> rlist = new List<dynamic>();

            if (_query.istree && whereModels.Count == 1 && deleteFlag != "1" && _query.export == false)
            {
                var list = db.Queryable<dynamic>().AS("[" + model.TableName + "]")
                    .Where(whereModels)
                    .OrderBy(orderby)
                    .ToList();

                List<dynamic> list1 = new List<dynamic>();

                foreach (var m in list)
                {
                    var setting = new JsonSerializerSettings
                    {
                        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                    };
                    var json = JsonConvert.SerializeObject(m, setting);

                    list1.Add(JsonConvert.DeserializeObject<dynamic>(json));
                }

                var tmpJson = JsonConvert.SerializeObject(list1);

                tmpJson = tmpJson.Replace("\"" + _query.treeid + "\":", "\"children\":null," + "\"id\":");
                if (_query.treeid != "parentId")
                {
                    tmpJson = tmpJson.Replace("\"" + _query.treeparentid + "\":", "\"parentId\":");
                }

                var tmpJsonObj = JsonConvert.DeserializeObject<List<dynamic>>(tmpJson);

                rlist = CreateTreeChildList(tmpJsonObj, 0);

                _query.per_page = list.Count;
                totalCount = list.Count;
            }
            else
            {
                List<dynamic> list = new List<dynamic>();

                if (_query.export)
                {
                    list = db.Queryable<dynamic>().AS("[" + model.TableName + "]")
               .Where(whereModels)
               .OrderBy(orderby)
               .ToList();
                }
                else
                {
                    list = db.Queryable<dynamic>().AS("[" + model.TableName + "]")
               .Where(whereModels)
               .OrderBy(orderby)
               .ToPageList(_query.page, _query.per_page, ref totalCount);
                }

                foreach (var m in list)
                {
                    var setting = new JsonSerializerSettings
                    {
                        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                    };
                    var json = JsonConvert.SerializeObject(m, setting);

                    rlist.Add(JsonConvert.DeserializeObject<dynamic>(json));
                }
            }

            model.ObjectData.DataSource = rlist;

            model.ObjectData.Meta.Page = _query.page;

            model.ObjectData.Meta.PerPage = _query.per_page;

            model.ObjectData.Meta.Total = totalCount;

            #region 下拉列表及相关的初始化data数据

            foreach (var m in model.ObjectData.Layout.TableColumn)
            {
                if (!string.IsNullOrEmpty(m.Sql))
                {
                    if (m.Type == "selects" || m.Type == "select" || m.Type == "radio" || m.Type == "switch")
                    {
                        m.Data = db.Ado.SqlQuery<dynamic>(m.Sql).ToList();
                        m.Sql = "";
                    }
                    else if (m.Type == "tree")
                    {
                        m.Sql = "";
                    }
                    else
                    {
                        m.Sql = "";
                    }
                }
            }

            #endregion

            return model;
        }

        private List<dynamic> CreateTreeChildList(List<dynamic> tmpdata, int parentId)
        {
            List<dynamic> treedatas = new List<dynamic>();

            var childsdata = tmpdata.Where(n => n.parentId == parentId).ToList();

            foreach (var t in childsdata)
            {
                List<dynamic> children = new List<dynamic>();

                if (tmpdata.Where(n => n.parentId == t.id).ToList().Count > 0)
                {
                    children = CreateTreeChildList(tmpdata, int.Parse(t.id.ToString()));
                }

                if (children.Count > 0)
                {
                    t.children = JToken.FromObject(children);
                }

                treedatas.Add(t);
            }

            return treedatas;
        }

        /// <summary>
        /// 获取编辑新增页面信息
        /// </summary>
        /// <param name="_id"></param>
        /// <returns></returns>
        public ApiPageModelViewModel.Data GetEditData(int _id)
        {
            Model model = db.Queryable<Model>().Where(p => p.ID == _id).First();

            var page = JsonConvert.DeserializeObject<ApiPageModelViewModel.Data>(model.EditData);

            if (page.Layout.colNumb == null || page.Layout.colNumb < 1)
            {
                page.Layout.colNumb = 1;
            }

            #region 下拉列表及相关的初始化data数据

                foreach (var m in page.Layout.Tabs[0].Data)
            {
                if (!string.IsNullOrEmpty(m.Sql))
                {
                    if (m.Type == "selects" || m.Type == "select" || m.Type == "radio" || m.Type == "switch")
                    {
                        m.Data = db.Ado.SqlQuery<dynamic>(m.Sql).ToList();
                        m.Sql = "";
                    }
                    else if (m.Type == "tree")
                    {
                        List<dynamic> treedatas = new List<dynamic>();
                        var tmpdata = db.Ado.SqlQuery<dynamic>(m.Sql).ToList();
                        m.Data = CreateTreeChild(tmpdata, 0);
                        m.Sql = "";
                    }
                    else if (m.Type == "parent")
                    {
                        List<dynamic> treedatas = new List<dynamic>();
                        var tmpdata = db.Ado.SqlQuery<dynamic>(m.Sql).ToList();
                        tmpdata.Add(new
                        {
                            ID = 0,
                            parentId = -1,
                            title = "根级"
                        });
                        m.Data = CreateTreeChild(tmpdata, -1);
                        m.Sql = "";
                    }
                    else
                    {
                        m.Sql = "";
                    }
                }
            }

            #endregion

            return page;
        }

        private dynamic CreateTreeChild(List<dynamic> tmpdata, int parentId)
        {
            List<dynamic> treedatas = new List<dynamic>();

            var childsdata = tmpdata.Where(n => n.parentId == parentId).ToList();

            foreach (var t in childsdata)
            {
                List<dynamic> children = new List<dynamic>();

                if (tmpdata.Where(n => n.parentId == t.ID).ToList().Count > 0)
                {
                    children = CreateTreeChild(tmpdata, t.ID);
                }

                treedatas.Add(new
                {
                    key = t.ID,
                    value = t.ID,
                    parentId = t.parentId,
                    title = t.title,
                    children = children
                });
            }

            return treedatas;
        }


        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="_id"></param>
        /// <param name="_query"></param>
        /// <returns></returns>
        public IActionResult Export(int _id, ApiModelsQuerys _query)
        {
            List<string> Exportpro = new List<string>();
            List<string> ExportTitles = new List<string>();

            var model = Model(_id, _query);

            var list = model.ObjectData.DataSource as List<dynamic>;

            foreach (var m in model.ObjectData.Layout.TableColumn)
            {
                if (m.HideInColumn == false)
                {
                    if (m.Type == "select" || m.Type == "radio" || m.Type == "switch")
                    {
                        if (!Exportpro.Contains(m.Key + "Name"))
                        {
                            Exportpro.Add(m.Key + "Name");
                            ExportTitles.Add(m.Title);
                        }
                    }
                    else
                    {
                        if (!Exportpro.Contains(m.Key))
                        {
                            Exportpro.Add(m.Key);
                            ExportTitles.Add(m.Title);
                        }
                    }
                }
            }

            var tmptypelist = model.ObjectData.Layout.TableColumn.Where(m => m.HideInColumn == false && (m.Type == "select" || m.Type == "radio" || m.Type == "switch")).ToList();

            foreach (JObject m in list)
            {
                foreach (var t in tmptypelist)
                {
                    string tmpstr = "";
                    string tmpid = m.Value<string>(t.Key);

                    if (!string.IsNullOrEmpty(tmpid))
                    {
                        List<dynamic> tmp = ((List<dynamic>)t.Data).Where(n => n.value.ToString() == tmpid).ToList();
                        if (tmp.Count > 0)
                        {
                            tmpstr = tmp[0].title.ToString();
                        }
                    }
                    if (!m.ContainsKey(t.Key + "Name"))
                    {
                        m.Add(t.Key + "Name", tmpstr);
                    }
                }
            }

            var tmpStream = ExcelHelper.DataToExcel(list, "", Exportpro, ExportTitles);
            MemoryStream ms = new MemoryStream(tmpStream);
            ms.Position = 0;
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = "export.xls" };
        }
        #endregion


        /// <summary>
        /// 获取models列表
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="per_page">没页记录数</param>
        /// <param name="sort">排序字段</param>
        /// <param name="order">排序字段对应正序倒序 asc desc</param>
        /// <param name="status">垃圾箱</param>
        /// <returns></returns>
        public Model GetModels(int page, int per_page, List<string> sort, List<string> order, bool status)
        {
            //model表 默认id=1 保存自己的列表信息（不许删除）
            Model model = db.Queryable<Model>().Where(p => p.ID == 14).First();

            if (model == null) throw Oops.Oh(SystemErrorCodes.E0003);

            return model;
        }

        /// <summary>
        /// 获取动态表单model设计模型
        /// </summary>
        /// <param name="_id"></param>
        /// <returns></returns>
        public dynamic GetModelDesign(int _id)
        {
            Model model = db.Queryable<Model>().Where(p => p.ID == _id).First();

            if (model == null) throw Oops.Oh(SystemErrorCodes.E0003);

            if (string.IsNullOrEmpty(model.DesignData))
            {
                return new { RouteName = model.RouteName, id = _id };
            }
            var tmp = JsonConvert.DeserializeObject<ApiDesignModel>(model.DesignData);
            tmp.Id = _id;
            return tmp;

        }

        /// <summary>
        /// 动态表单设计保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Model PostModelDesign(ApiDesignModel model)
        {
            bool insertmenu = false;

            Model rs = new Model();
            rs.RouteName = model.RouteName;
            rs.DesignData = JsonConvert.SerializeObject(model);

            #region 列表界面配置

            List<dynamic> tableColumn = new List<dynamic>();
            List<dynamic> tableToolBar = new List<dynamic>();
            List<dynamic> batchToolBar = new List<dynamic>();
            List<dynamic> dataSource = new List<dynamic>();

            foreach (var m in model.Fields)
            {
                tableColumn.Add(new
                {
                    title = m.Title,
                    dataIndex = m.Name,
                    key = m.Name,
                    type = m.Type,
                    hideInColumn = m.HideInColumn == null ? false : m.HideInColumn.Value,
                    sql = m.Data
                });
            }

            if (model.ListAction.Count > 0)
            {
                List<dynamic> actions = new List<dynamic>();

                foreach (var m in model.ListAction)
                {
                    actions.Add(new
                    {
                        component = "button",
                        text = m.Title,
                        type = m.Type,
                        action = m.Action,
                        uri = m.Uri,
                        method = m.Method,
                        usetype = "nodel"
                    });
                }

                foreach (var m in model.BatchToolbarTrashed)
                {
                    actions.Add(new
                    {
                        component = "button",
                        text = m.Title,
                        type = m.Type,
                        action = m.Action,
                        uri = m.Uri,
                        method = m.Method,
                        usetype = "del"
                    });
                }

                tableColumn.Add(new
                {
                    title = "操作",
                    dataIndex = "actions",
                    key = "actions",
                    type = "actions",
                    actions = actions
                });
            }

            foreach (var m in model.TableToolbar)
            {
                tableToolBar.Add(new
                {
                    component = "button",
                    text = m.Title,
                    type = m.Type,
                    action = m.Action,
                    uri = m.Uri,
                    method = m.Method
                });
            }

            foreach (var m in model.BatchToolbar)
            {
                batchToolBar.Add(new
                {
                    component = "button",
                    text = m.Title,
                    type = m.Type,
                    action = m.Action,
                    uri = m.Uri,
                    method = m.Method,
                    usetype = "nodel"
                });
            }

            foreach (var m in model.BatchToolbarTrashed)
            {
                batchToolBar.Add(new
                {
                    component = "button",
                    text = m.Title,
                    type = m.Type,
                    action = m.Action,
                    uri = m.Uri,
                    method = m.Method,
                    usetype = "del"
                });
            }

            dynamic listData = new
            {
                page = new
                {
                    tableName = model.RouteName,
                    title = model.MenuName + "列表",
                    type = "basicList",
                    searchBar = true,
                    trash = false
                },
                layout = new
                {
                    tableColumn = tableColumn,
                    tableToolBar = tableToolBar,
                    batchToolBar = batchToolBar
                },
                dataSource = dataSource,
                meta = new { }
            };

            rs.Data = JsonConvert.SerializeObject(listData);

            #endregion

            #region 编辑新增界面

            List<dynamic> tabs = new List<dynamic>();
            List<dynamic> tabsfields = new List<dynamic>();
            List<dynamic> actionsedit = new List<dynamic>();
            List<dynamic> actionopers = new List<dynamic>();

            foreach (var m in model.Fields)
            {
                if (m.HideInForm == false)
                {
                    tabsfields.Add(new
                    {
                        title = m.Title,
                        dataIndex = m.Name,
                        key = m.Name,
                        type = m.Type,
                        hideInColumn = m.HideInColumn == null ? false : m.HideInColumn,
                        editDisabled = m.EditDisabled,
                        requiredInForm = m.RequiredInForm,
                        data = new List<dynamic>(),
                        sql = m.Data
                    });
                }
            }

            tabs.Add(new
            {
                name = "Basic",
                title = "基础信息",
                data = tabsfields
            });

            foreach (var m in model.EditAction)
            {
                actionopers.Add(new
                {
                    component = "button",
                    text = m.Title,
                    type = m.Type,
                    action = m.Action,
                    uri = m.Uri,
                    method = m.Method
                });
            }

            actionsedit.Add(new
            {
                name = "actions",
                title = "actions",
                data = actionopers
            });


            dynamic editData = new
            {
                page = new
                {
                    title = model.MenuName + "编辑",
                    type = "page"
                },
                layout = new
                {
                    tabs = tabs,
                    actions = actionsedit,
                    colNumb= model.FormColumns
                }
            };

            rs.EditData = JsonConvert.SerializeObject(editData);

            #endregion

            if (model.Id == 0)
            {
                rs.TableName = model.RouteName;

                rs.CreateTime = DateTime.Now;

                rs.CreateUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));

                Model newrs = db.Insertable(rs).ExecuteReturnEntity() ?? throw Oops.Oh(SystemErrorCodes.E0010);

                rs.ID = newrs.ID;

                insertmenu = true;
            }
            else
            {
                if (string.IsNullOrEmpty(db.Queryable<Model>().First(n => n.ID == model.Id).DesignData))
                {
                    insertmenu = true;
                }

                rs.ID = model.Id;
                rs.ModifyTime = DateTime.Now;
                rs.ModifyUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
                db.Updateable(rs).IgnoreColumns(ignoreAllNullColumns: true).IgnoreColumns("CreateTime", "CreateUserID").ExecuteCommand();
            }

            if (insertmenu)
            {
                #region 新增菜单及获取详情接口、保存接口

                MenuRule rule = new MenuRule();
                rule.ParentMenuRuleID = 0;
                rule.Name = model.MenuName + "管理";
                rule.Api = "/api/" + rs.RouteName;
                rule.Icon = "icon-table";
                rule.Path = "/basic-list/api/" + rs.RouteName;
                rule.HideChildrenInMenu = 0;
                rule.HideInMenu = 0;
                rule.FlatMenu = 0;
                rule.Type = 0;
                rule.CreateTime = DateTime.Now;
                rule.CreateUserID = rs.CreateUserID;
                rule.DeleteFlag = 0;
                rule.HttpMethod = "post";

                var tmprule = db.Insertable(rule).ExecuteReturnEntity();

                rule.ID = tmprule.ID;

                MenuRule rule1 = new MenuRule();
                rule1.ParentMenuRuleID = rule.ID;
                rule1.Name = model.MenuName + "编辑";
                rule1.Api = "/api/" + rs.RouteName + "/info/";
                rule1.Icon = "icon-table";
                rule1.Path = "/basic-list/api/" + rs.RouteName + "/info/:id";
                rule1.HideChildrenInMenu = 0;
                rule1.HideInMenu = 1;
                rule1.FlatMenu = 0;
                rule1.Type = 0;
                rule1.CreateTime = DateTime.Now;
                rule1.CreateUserID = rs.CreateUserID;
                rule1.DeleteFlag = 0;
                rule1.HttpMethod = "get";

                db.Insertable(rule1).ExecuteReturnEntity();

                MenuRule rule2 = new MenuRule();
                rule2.ParentMenuRuleID = rule.ID;
                rule2.Name = model.MenuName + "保存";
                rule2.Api = "/api/" + rs.RouteName + "/save";
                rule2.Icon = "icon-table";
                rule2.Path = "/api/" + rs.RouteName + "/save";
                rule2.HideChildrenInMenu = 0;
                rule2.HideInMenu = 1;
                rule2.FlatMenu = 0;
                rule2.Type = 0;
                rule2.CreateTime = DateTime.Now;
                rule2.CreateUserID = rs.CreateUserID;
                rule2.DeleteFlag = 0;
                rule2.HttpMethod = "post";

                db.Insertable(rule2).ExecuteReturnEntity();

                MenuRule rule3 = new MenuRule();
                rule3.ParentMenuRuleID = rule.ID;
                rule3.Name = model.MenuName + "删除";
                rule3.Api = "/api/" + rs.RouteName + "/delete";
                rule3.Icon = "icon-table";
                rule3.Path = "/api/" + rs.RouteName + "/delete";
                rule3.HideChildrenInMenu = 0;
                rule3.HideInMenu = 1;
                rule3.FlatMenu = 0;
                rule3.Type = 0;
                rule3.CreateTime = DateTime.Now;
                rule3.CreateUserID = rs.CreateUserID;
                rule3.DeleteFlag = 0;
                rule3.HttpMethod = "post";

                db.Insertable(rule3).ExecuteReturnEntity();

                MenuRule rule4 = new MenuRule();
                rule4.ParentMenuRuleID = rule.ID;
                rule4.Name = model.MenuName + "禁用";
                rule4.Api = "/api/" + rs.RouteName + "/disable";
                rule4.Icon = "icon-table";
                rule4.Path = "/api/" + rs.RouteName + "/disable";
                rule4.HideChildrenInMenu = 0;
                rule4.HideInMenu = 1;
                rule4.FlatMenu = 0;
                rule4.Type = 0;
                rule4.CreateTime = DateTime.Now;
                rule4.CreateUserID = rs.CreateUserID;
                rule4.DeleteFlag = 0;
                rule4.HttpMethod = "post";

                db.Insertable(rule4).ExecuteReturnEntity();

                MenuRule rule5 = new MenuRule();
                rule5.ParentMenuRuleID = rule.ID;
                rule5.Name = model.MenuName + "恢复";
                rule5.Api = "/api/" + rs.RouteName + "/restore";
                rule5.Icon = "icon-table";
                rule5.Path = "/api/" + rs.RouteName + "/restore";
                rule5.HideChildrenInMenu = 0;
                rule5.HideInMenu = 1;
                rule5.FlatMenu = 0;
                rule5.Type = 0;
                rule5.CreateTime = DateTime.Now;
                rule5.CreateUserID = rs.CreateUserID;
                rule5.DeleteFlag = 0;
                rule5.HttpMethod = "post";

                db.Insertable(rule5).ExecuteReturnEntity();

                MenuRule rule6 = new MenuRule();
                rule6.ParentMenuRuleID = rule.ID;
                rule6.Name = model.MenuName + "导出";
                rule6.Api = "/api/" + rs.RouteName + "/export";
                rule6.Icon = "icon-table";
                rule6.Path = "/api/" + rs.RouteName + "/export";
                rule6.HideChildrenInMenu = 0;
                rule5.HideInMenu = 1;
                rule6.FlatMenu = 0;
                rule6.Type = 0;
                rule6.CreateTime = DateTime.Now;
                rule6.CreateUserID = rs.CreateUserID;
                rule6.DeleteFlag = 0;
                rule6.HttpMethod = "post";

                db.Insertable(rule6).ExecuteReturnEntity();

                #endregion
            }

            return rs;
        }
    }
}
